package com.sxm.yiwei.activitis;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.view.ContextThemeWrapper;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.BaseIntents;
import com.sxm.yiwei.tools.CropPictures;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FWEvaluateActivity extends BaseActivity implements View.OnClickListener{

    private ImageView x1,x2,x3,x4,x5;
    private ImageView evaluateback;
    private ImageView img1,img2,img3;
    private EditText edit;
    private CheckBox box;
    private Button toupbt;
    private String id;
    private ImageView head;
    private String p ="5";
    private List<String> imglist = new ArrayList();
    private static final int PHOTO_TEXT = 3022;
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    /*用来标识请求照相功能的activity*/
    private static final int CAMERA_WITH_DATA = 3023;
    private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
    private double currentIndex;
    private Bitmap photo;
    private String path1;
    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private String appId;
    private String is ="0";
    private AlertDialog dialog;
    private AlertDialog dialog1;
    private BaseIntents baseIntents;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fwevaluate);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        initEvaluateView();
        baseIntents = new BaseIntents();
        Intent intent = getIntent();
        String avatar = intent.getStringExtra("avatar");
        x.image().bind(head, InternetAddressUtis.IMG_URL+avatar);
        id = intent.getStringExtra("id");
    }

    private void initEvaluateView() {
        head = (ImageView) findViewById(R.id.fw_evaluatehead);
        x1 = (ImageView) findViewById(R.id.fw_evaluate_x1);
        x2 = (ImageView) findViewById(R.id.fw_evaluate_x2);
        x3 = (ImageView) findViewById(R.id.fw_evaluate_x3);
        x4 = (ImageView) findViewById(R.id.fw_evaluate_x4);
        x5 = (ImageView) findViewById(R.id.fw_evaluate_x5);
        evaluateback = (ImageView) findViewById(R.id.fw_evalute_back);
        img1 = (ImageView) findViewById(R.id.fw_evaluae_img1);
        img2 = (ImageView) findViewById(R.id.fw_evaluae_img2);
        img3 = (ImageView) findViewById(R.id.fw_evaluae_img3);
        edit = (EditText) findViewById(R.id.fw_evaluate_edit);
        box = (CheckBox) findViewById(R.id.fw_evaluate_box);
        toupbt = (Button) findViewById(R.id.fw_evaluate_toupbt);

        backmain = (ImageView) findViewById(R.id.fwevaluate_backmain);
        backmain.setOnClickListener(this);
        img1.setOnClickListener(this);
        img2.setOnClickListener(this);
        img3.setOnClickListener(this);
        box.setOnClickListener(this);
        x1.setOnClickListener(this);
        x2.setOnClickListener(this);
        x3.setOnClickListener(this);
        x4.setOnClickListener(this);
        x5.setOnClickListener(this);
        toupbt.setOnClickListener(this);
        evaluateback.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fwevaluate_backmain:

                startActivity(new Intent(FWEvaluateActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.fw_evaluae_img1:
                currentIndex= 1;
                doPickPhotoAction();
                break;
            case R.id.fw_evaluae_img2:
                currentIndex= 2;
                doPickPhotoAction();
                break;
            case R.id.fw_evaluae_img3:
                currentIndex= 3;
                doPickPhotoAction();
                break;
            case R.id.fw_evaluate_box:
                if (!box.isChecked()){
                    box.setChecked(false);
                }else {}
                if (box.isChecked()==true){
                    is="1";
                }else {
                    is="0";
                }
                break;
            case R.id.fw_evaluate_toupbt:
                if (p!=null){
                    AlertDialog.Builder builder = new AlertDialog.Builder(FWEvaluateActivity.this,R.style.NoBackGroundDialog);
                    View view = LayoutInflater.from(FWEvaluateActivity.this).inflate(R.layout.progress_dialog, null);
                    ProgressBar diapro = (ProgressBar) view.findViewById(R.id.pro_dia);
                    builder.setView(view);
                    dialog1 = builder.create();

                    dialog1.show();

                    commentService();
                }else {
                    Toast.makeText(this, "请评分后再提交", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.fw_evalute_back:
                finish();
                break;
            case R.id.fw_evaluate_x1:
                p="1";
                x1.setImageResource(R.mipmap.fabupingjia2);
                x2.setImageResource(R.mipmap.fabupingjia);
                x3.setImageResource(R.mipmap.fabupingjia);
                x4.setImageResource(R.mipmap.fabupingjia);
                x5.setImageResource(R.mipmap.fabupingjia);

                break;
            case R.id.fw_evaluate_x2:
                p="2";
                x1.setImageResource(R.mipmap.fabupingjia2);
                x2.setImageResource(R.mipmap.fabupingjia2);
                x3.setImageResource(R.mipmap.fabupingjia);
                x4.setImageResource(R.mipmap.fabupingjia);
                x5.setImageResource(R.mipmap.fabupingjia);
                break;
            case R.id.fw_evaluate_x3:
                p="3";
                x1.setImageResource(R.mipmap.fabupingjia2);
                x2.setImageResource(R.mipmap.fabupingjia2);
                x3.setImageResource(R.mipmap.fabupingjia2);
                x3.setImageResource(R.mipmap.fabupingjia);
                x3.setImageResource(R.mipmap.fabupingjia);
                break;
            case R.id.fw_evaluate_x4:
                p="4";
                x1.setImageResource(R.mipmap.fabupingjia2);
                x2.setImageResource(R.mipmap.fabupingjia2);
                x3.setImageResource(R.mipmap.fabupingjia2);
                x4.setImageResource(R.mipmap.fabupingjia2);
                x5.setImageResource(R.mipmap.fabupingjia);
                break;
            case R.id.fw_evaluate_x5:
                p="5";
                x1.setImageResource(R.mipmap.fabupingjia2);
                x2.setImageResource(R.mipmap.fabupingjia2);
                x3.setImageResource(R.mipmap.fabupingjia2);
                x4.setImageResource(R.mipmap.fabupingjia2);
                x5.setImageResource(R.mipmap.fabupingjia2);
                break;
        }
    }
        // 评价服务
    private void commentService() {
        String text = String.valueOf(edit.getText());
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.PINGJIASERVICE);
        params.addHeader("Content-Type","multipart/form-data");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);


        /**
         * multipart/form-data 上传文件时 一定要加上
         *   params.setMultipart(true);
         */

        params.addBodyParameter("orderId",id);
        params.addBodyParameter("score",p);
        params.addBodyParameter("content",text);
        params.addBodyParameter("anonymous",is);
        if (imglist.size()!=0){
            for (int i = 0; i < imglist.size(); i++) {
                params.addBodyParameter("comment",new File(imglist.get(i)));
            }
        }else {}

        params.setMultipart(true);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                dialog1.dismiss();
                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    Toast.makeText(FWEvaluateActivity.this, "评价成功", Toast.LENGTH_SHORT).show();
                    finish();
                }else {}
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ErrType.errType(FWEvaluateActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {

            }
        });
    }

    private void doPickPhotoAction() {
        final Context context = this;
        AlertDialog.Builder b1 = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.picture_dialog, null);
        b1.setView(view);

        TextView camere = (TextView) view.findViewById(R.id.picdia_camere);
        TextView pic = (TextView) view.findViewById(R.id.picdia_pic);
        TextView cancel1 = (TextView) view.findViewById(R.id.picdia_cancel);

        final AlertDialog dialog1 = b1.create();
        Window window = dialog1.getWindow();
        camere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String status= Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
                    // index=0;
                    baseIntents.doTakePhoto();// 用户点击了从照相机获取
                    dialog1.dismiss();
                }
                else{
                    Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseIntents.doPickPhotoFromGallery();// 从相册中去获取
                dialog1.dismiss();
            }
        });
        cancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });
        dialog1.show();
        window.setGravity(Gravity.BOTTOM);
    }

    // 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
                //final Bitmap photo = data.getParcelableExtra("data");
                Bitmap photo = data.getParcelableExtra("data");
                //  sengimg.setImageBitmap(photo);
                String s = CropPictures.saveBitmapFile(photo, new BaseIntents().getPhotoFileName());
                imglist.add(s);
                if (currentIndex ==1){
                   img1.setImageBitmap(photo);
                }else if (currentIndex ==2){
                    img2.setImageBitmap(photo);
                }else if (currentIndex ==3){
                    img3.setImageBitmap(photo);
                }
                break;
            }
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                baseIntents.doCropPhoto(baseIntents.mCurrentPhotoFile);
                break;
            }
            case PHOTO_TEXT:
                Uri data1 = data.getData();
                if (!TextUtils.isEmpty(data1.getAuthority())){
                    ContentResolver resolver = getContentResolver();
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, data1);
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(data1, proj, null, null, null);
                        if (cursor==null){
                            Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }else {
                            cursor.moveToFirst();
                            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            //图片路径
                            path1 = cursor.getString(column_index);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    path1 = data1.getPath();
                }
                File file = new File(path1);
                baseIntents.doCropPhoto(file);
                break;

        }

    }

}
